package com.bawei.property.vm

import androidx.lifecycle.viewModelScope
import com.bawei.common.vm.BaseViewModel
import com.bawei.property.entity.CarImageEntity
import com.bawei.property.entity.ColorValue
import com.bawei.property.entity.ParkValue
import com.bawei.property.intent.ParkViewIntent
import com.bawei.property.model.ParkApplyRepository
import com.bawei.property.state.ParkUiState
import com.blankj.utilcode.util.GsonUtils
import com.blankj.utilcode.util.LogUtils
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.async
import kotlinx.coroutines.awaitAll
import kotlinx.coroutines.cancel
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.launch
import okhttp3.MediaType.Companion.toMediaTypeOrNull
import okhttp3.MultipartBody
import okhttp3.RequestBody.Companion.asRequestBody
import java.io.File

/**
 * Author: Jason Zhang
 * Date: 2024/12/20
 * Desc: 车位模块的ViewModel
 */
class ParkViewModel: BaseViewModel<ParkViewIntent>() {

    private val _uiState = MutableStateFlow<ParkUiState>(ParkUiState.NoneState)
    val uiState: StateFlow<ParkUiState> = _uiState.asStateFlow()

    private val mRepository = ParkApplyRepository()

    override fun dispatchIntent(intent: ParkViewIntent) {
        when(intent){
            is ParkViewIntent.LoadParkList -> loadParkList()
            is ParkViewIntent.LoadColorList -> loadColorList()
            is ParkViewIntent.UploadCarImages -> uploadImages(intent.list)
            is ParkViewIntent.SubmitParkInfo -> submitParkInfo()


        }

    }

    private fun submitParkInfo(){



    }


    /**
     * 批量多任务上传
     */
    private fun uploadImages(list: List<CarImageEntity>) {
        viewModelScope.launch(Dispatchers.IO) {
            try {
                //开启多个任务，异步并发上传图片
                val deferredResults= list.map {
                    async {
                        var builder = MultipartBody.Builder()
                        builder.setType(MultipartBody.FORM)
                        //将文件转成RequestBody对象
                        var body = File(it.path).asRequestBody("multipart/form-data".toMediaTypeOrNull()) //指定使用Form表单提交数据
                        builder.addFormDataPart("file", it.name, body)
                        mRepository.uploadImagesList(builder.build().parts as MutableList<MultipartBody.Part>)
                    }
                }

                //等待所有任务执行完毕
                var results = deferredResults.awaitAll()
                LogUtils.i("图片上传结果返回：${GsonUtils.toJson(results)}")

                //判断是否全部上传成功
                var allUploadSuccess = false
                var imgUrls = mutableListOf<String>()
                results.forEachIndexed { index, entity ->
                    if (entity.statuesCode == "200"){
                        allUploadSuccess = true
                        imgUrls.add("http://10.161.9.80:7035/${list[index].name}")
                    }else{
                        allUploadSuccess = false
                    }
                }

                //发送UI状态给View层
                if (allUploadSuccess && imgUrls.size > 0){
                    _uiState.value = ParkUiState.UploadImageSuccess(imgUrls)
                } else {
                    _uiState.value = ParkUiState.UploadImageFail("上传失败！！")
                }
            } catch (e:Exception){
                e.printStackTrace()
                _uiState.value = ParkUiState.UploadImageFail("上传失败！！")
            } finally {
                cancel()
            }
        }
    }


    /**
     * 获取颜色列表
     */
    private fun loadColorList(){
        viewModelScope.launch(Dispatchers.IO) {
            try {
                var result = mRepository.getColorList()
                if (result.statuesCode == "200"){
                    var newList = mutableListOf<ColorValue>()
                    var colorList = result.getValues()
                    newList.addAll(colorList)
                    _uiState.value = ParkUiState.LoadColorListSuccess(newList)
                } else {
                    _uiState.value = ParkUiState.LoadColorListFail(result.msg ?: "接口请求失败！")
                }
            } catch (e: Exception){
                _uiState.value = ParkUiState.LoadColorListFail("接口异常，请联系客服！")
            }finally {
                cancel()
            }
        }
    }

    /**
     * 获取车位列表数据
     */
    private fun loadParkList() {
        viewModelScope.launch(Dispatchers.IO) {
            try {
                var result = mRepository.getCarApplyList()
                if (result.statuesCode == "200"){
                    var newList = mutableListOf<ParkValue>()
                    var parkList = result.getValues()
                    newList.addAll(parkList)
                    //添加模拟数据
                    for (index in 0 .. 20){
                        newList.add(ParkValue().apply {
                            parkUser = index % 2
                            parkTime = "2025-12-20T01:34:10Z"
                            parkEnd = "2026-12-21"
                            parkId = index * 22
                            parkName = "车主${index}"
                            parkStart = "2024-12-20"
                        })
                    }
                    _uiState.value = ParkUiState.LoadParkListSuccess(newList)
                }else{
                  _uiState.value = ParkUiState.LoadParkListFail(result.msg ?: "接口请求失败！")
                }
            } catch (e: Exception){
                _uiState.value = ParkUiState.LoadParkListFail("接口异常，请联系客服！")
            }finally {
                cancel()
            }
        }
    }


}